<?php
class SearchController extends AppController {
	
	public $names = "SearchController";
	public $uses = array("MongoArticle", "MetadataFields");
	
	public function index() {
		$metadataFieldsList = $this->MetadataFields->getAlls();
		$this->set(compact('metadataFieldsList'));
	}
	
	public function searchArticle() {
		$collectionName = "article";
		$fieldsList = $this->MetadataFields->getFieldsList();
		$data = $this->request->data;
		$dataCondition = $this->generateDataCondition($data);
		
		$resultList;
		if (array_key_exists("all", $dataCondition)) {
			$resultList = $this->MongoArticle->searhAllFields($collectionName, $fieldsList, $dataCondition["all"]);
		} else {
			$resultList = $this->MongoArticle->searchMetaData($collectionName, $dataCondition, "and");
		}
// 		$this->ajaxResponse(json_encode($resultList, JSON_UNESCAPED_UNICODE));
// 		$this->ajaxResponse(json_encode($dataCondition, JSON_UNESCAPED_UNICODE));
		
// 		$refineBy = $this->MongoArticle->refineBy($collectionName, $dataCondition, "refine", "authors.FNameNative", "or");
		$refineBy = $this->MongoArticle->refineAllFieldsBy($collectionName, $fieldsList, $dataCondition["all"], "refine", "authors.FNameNative");
		$this->ajaxResponse(json_encode($refineBy, JSON_UNESCAPED_UNICODE));
	}
	
	private function generateDataCondition($data) {
		$tempDataCondition = array();
		$i = 0;
		foreach ($data as $key => $value) {
			if ($i % 2 == 0) {
				$tempDataCondition[$value] = "";
			} else {
				end($tempDataCondition);
				$tempDataCondition[key($tempDataCondition)] = $value;
			}
			$i++;
		}
		$dataCondition = array();
		foreach ($tempDataCondition as $key => $value) {
			if (($key != "") && ($value != "")) {
				$dataCondition[$key] = $value;
			}
		}
		return $dataCondition;
	}
	
}